const fs = require('fs')
const path = require('path')

// ----------- readFile -----------
/**
 * data1.txt的时候输出错误:
 * Error: ENOENT: no such file or directory, open 'C:\Leslie\NodeJs\1-NodeJs-Core-Module\codes\FS\data1.txt'
 */
fs.readFile(path.resolve('data.txt'), 'utf-8', (
  err /**错误优先: 第一个参数是err */,
  data
) => {
  if (!err) {
    // err: null
    console.info(data) // 荣光无限
  } else {
    console.info(err)
  }
})

// ----------- writeFile -----------
fs.writeFile(
  'data-write.txt',
  'Hello React\n',
  {
    mode: 438,
    flag: 'w+', // w+: 内容清空再写入, r+: 不会清空
    encoding: 'utf-8',
  },
  (err, data) => {
    if (!err) {
      fs.readFile(path.resolve('data-write.txt'), 'utf-8', (err, data) => {
        console.info('data in data-write: ', data)
      })
    }
  }
)

// ----------- appendFile -----------
fs.appendFile('data-write.txt', 'Hello Vue\n', 'utf-8', (err, data) => {
  if (!err) {
    fs.readFile(path.resolve('data-write.txt'), 'utf-8', (err, data) => {
      console.info('data in data-write: ', data)
    })
  }
})

// ----------- copyFile -----------
fs.copyFile('data.txt', 'data-copy.txt', () => {
  console.info('Copy OK')
})

// ----------- watchFile -----------
fs.watchFile(
  'data.txt',
  {
    interval: 20, // 毫秒
  },
  (curr, prev) => {
    // 被修改了
    if (curr.mtime !== prev.mtime) {
      console.info('File has been updated')
      fs.unwatchFile('data.txt')
    }
  }
)
